package java_code.druid;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class druidJDBCUtils {//JDBCUtils.properties
    //读取配置文件的内容到这来把下面的字符串替换,解决硬编码问题
    //static String url;//null
    //static String user;//null
    //static String password;//null
    //static ComboPooledDataSource pool;//null
    private static DataSource dataSource;//null,dataSource-pool

    public static DataSource getDataSource() {
        return dataSource;
    }

    static {
        try {
            //dataSource = new ComboPooledDataSource();

            Properties p = new Properties();
            InputStream is = druidJDBCUtils.class.getClassLoader().getResourceAsStream("java_code\\druid\\druid.properties");//注意路径的问题
            p.load(is);//p
            dataSource = DruidDataSourceFactory.createDataSource(p);
            //Connection connection = dataSource.getConnection();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection() {
        try {
            //Class.forName("com.mysql.jdbc.Driver");//Driver.class
            //Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db3", "root", "root");
            //修改JDBC工具类得到连接方法,改为来自连接池
            //Connection connection = DriverManager.getConnection(url, user, password);
            //ComboPooledDataSource pool = new ComboPooledDataSource();
            Connection connection = dataSource.getConnection();

            return  connection;
        } catch(Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    public static void close(ResultSet resultSet,Statement statement,Connection connection) {
        if (resultSet!=null){
            try {
                resultSet.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (statement!=null){
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        //connection.notnull
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
